{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mapping\n",
    "\n",
    "This notebook uses the cartopy package to generate maps of the data variables of interest across the Arctic Ocean. It uses data contained in the xarray file generated in the [data wrangling](https://nicolejkeeney.github.io/icesat2-book/data_wrangling.html) notebook with all data provided on the same Polar Stereographic grid to simplify the analysis/mapping.\n",
    "\n",
    "**Input**:\n",
    " - xarray dataset from the jupyter book's google bucket\n",
    " \n",
    " \n",
    " **Output**: \n",
    "  - maps of the Arctic with data overlayed"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{tip}\n",
    "Try running this notebook in Google Colab! Toggle over the rocketship icon at the top of the page and click Colab to open a new window and run the notebook. <br><br>To run a single cell, type **Shift+Enter**. To run the whole notebook, under **Runtime** click **Run all**. Note that you will have to run the notebook from the very beginning and load all the Google Colab dependencies for the code to work.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "#this cell will load dependencies for running the notebook in Google Colab\n",
    "#this cell may take a while to run\n",
    "import sys\n",
    "\n",
    "#if code is running in google colab, run these cells to install neccessary libraries\n",
    "if 'google.colab' in sys.modules: \n",
    "    !apt-get install -qq libgdal-dev libproj-dev\n",
    "    !pip install --no-binary shapely shapely --force\n",
    "    !pip install -q pyproj\n",
    "    !pip install cartopy\n",
    "    !pip install netcdf4\n",
    "    !pip install xarray==0.16.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import notebook dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import xarray as xr\n",
    "import pandas as pd\n",
    "import numpy.ma as ma\n",
    "import cartopy.crs as ccrs\n",
    "import cartopy.feature as cfeature\n",
    "import pyproj\n",
    "from textwrap import wrap\n",
    "\n",
    "#axes needed for plotting\n",
    "from matplotlib.axes import Axes\n",
    "from cartopy.mpl.geoaxes import GeoAxes\n",
    "GeoAxes._pcolormesh_patched = Axes.pcolormesh\n",
    "\n",
    "#remove warnings to improve display\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "#increase resolution for notebook outputs\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "import matplotlib as mpl\n",
    "mpl.rcParams['figure.dpi'] = 125"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data into notebook\n",
    "Copy file from the book's google bucket and load into an xarray dataset. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "!gsutil -m cp gs://is2-pso-seaice/icesat2-book-data.nc ./\n",
    "dataset = xr.open_dataset('icesat2-book-data.nc')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot one month of data "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{note}\n",
    "Cartopy has a bug and cannot produce a contour plot on a rotated grid. Here we use a workaround from stackexchange: [https://stackoverflow.com/questions/55062406/cartopy-fails-to-correctly-contour-data-on-rotated-grid](https://stackoverflow.com/questions/55062406/cartopy-fails-to-correctly-contour-data-on-rotated-grid)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Define function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plotOneMonth(dataset, dataVar, month, minval, maxval, cbarTicks = None, cmap = 'viridis', figPath = None): \n",
    "    \"\"\"Plots map of the arctic on North Pole Stereo projection with one month of data overlayed, along with the sea ice edge for each month.\n",
    "   \n",
    "    Args:\n",
    "        dataset (xr Dataset): dataset from google bucket\n",
    "        dataVar (str): variable of interest\n",
    "        month (str): month and year of interest, i.e. 'Dec 2019' (does not need to be in any particular format)\n",
    "        minval, maxval (int): minimum and maximum values for the data variable \n",
    "        cbarTicks (list or np array of length 2): ticks to use on colorbar (default to [minval + 1, maxval +1])\n",
    "        cmap (str, optional): color map (default to viridis)\n",
    "        figPath (str, optional): path to save fig (default to None)\n",
    "        \n",
    "    Returns:\n",
    "        Figure displayed in notebook \n",
    "    \n",
    "    \"\"\"\n",
    "    \n",
    "    #define projection and transform\n",
    "    proj = ccrs.NorthPolarStereo(central_longitude = -45)\n",
    "    transform = ccrs.PlateCarree()\n",
    "    \n",
    "    #initialize the figure and axes \n",
    "    fig = plt.figure(figsize=(6, 6))\n",
    "    ax = plt.axes(projection = proj)\n",
    "    \n",
    "    #define arguments if not inputted \n",
    "    cbarTicks = np.arange(minval, maxval + 1, 1) if cbarTicks is None else cbarTicks\n",
    "    \n",
    "    #plot sea ice concentraion \n",
    "    SICarray = dataset['seaice_conc_monthly_cdr'].sel(time = month).where(dataset['region_mask']!=21) #dont plot contour along coastlines\n",
    "    \n",
    "    #stackexchange workaround for plotting on a rotated grid\n",
    "    lonGreater = ma.masked_greater(SICarray.longitude.values, -0.01)\n",
    "    lonLesser = ma.masked_less(SICarray.longitude.values, 0)\n",
    "    latGreater = ma.MaskedArray(SICarray.latitude.values, mask = lonGreater.mask)\n",
    "    latLesser = ma.MaskedArray(SICarray.latitude.values, mask = lonLesser.mask)\n",
    "    dataGreater = ma.MaskedArray(SICarray.values[0], mask = lonGreater.mask)\n",
    "    dataLesser = ma.MaskedArray(SICarray.values[0], mask = lonLesser.mask)\n",
    "    \n",
    "    #plot contour using each part of the 2 masked data sets\n",
    "    im2a = ax.contour(lonGreater, latGreater, dataGreater, levels = [0.5], transform = transform, colors = 'magenta', linewidths = 0.9, zorder=5, alpha=1)\n",
    "    im2b = ax.contour(lonLesser, latLesser, dataLesser, levels = [0.5], transform = transform, colors = 'magenta', linewidths = 0.9, zorder=5, alpha=1)\n",
    "    #im = ax.contour(SICarray.longitude.values, SICarray.latitude.values, SICarray.values[0], levels = [0.15], transform = transform, colors = 'magenta', linewidths = 0.8, zorder=15, alpha=1)\n",
    "    \n",
    "    #plot the data\n",
    "    dataset[dataVar].where(dataset['seaice_conc_monthly_cdr'] > 0.5).sel(time = month).plot(x = 'longitude', y = 'latitude', vmin = minval, vmax = maxval, extend = 'both', \n",
    "                    ax = ax, add_colorbar = True, transform = transform, zorder = 2, cmap = cmap, \n",
    "                    cbar_kwargs = {'label': \"\\n\".join(wrap(dataset[dataVar].attrs['long_name'] + ' (' + dataset[dataVar].attrs['units'] + ')', 50)), 'orientation': 'horizontal', 'shrink': 0.75, 'pad': 0.025})\n",
    "    \n",
    "    #add features to the map\n",
    "    ax.coastlines(linewidth=0.15, color = 'black', zorder = 10) #add coastlines \n",
    "    ax.add_feature(cfeature.LAND, color ='0.95', zorder = 5) #add land \n",
    "    ax.add_feature(cfeature.LAKES, color = 'grey', zorder = 5) #add lakes \n",
    "    ax.gridlines(draw_labels = False, linewidth = 0.25, color = 'gray', alpha = 0.7, linestyle = '--', zorder = 6) #add gridlines\n",
    "    ax.set_extent([-179, 179, 55, 90], crs = transform) #zoom in so map only displays the Arctic\n",
    "    ax.set_title(\"\\n\".join(wrap(month + \": \" + dataset[dataVar].attrs['long_name'], 38)), fontsize = 'x-large')\n",
    "    \n",
    "    #save figure\n",
    "    if figPath != None:\n",
    "        plt.savefig(figPath, dpi = 200)\n",
    "        \n",
    "    #display figure\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Call function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plotOneMonth(dataset, dataVar = 'ice_thickness_filled', month = 'Feb 2019', minval = 0, maxval  = 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also restrict the data by using the <span style=\"color:darkmagenta; font-family: Courier\">restrictRegionally</span> function from the [regional analysis](https://nicolejkeeney.github.io/icesat2-book/regional_analysis.html) notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#function from regional_analysis notebook\n",
    "def restrictRegionally(dataset, regionKeyList): \n",
    "    \"\"\"Restrict dataset to input regions.\n",
    "    \n",
    "    Args: \n",
    "        dataset (xr Dataset): dataset generated by Load_IS2 notebook\n",
    "        regionKeyList (list): list of region keys to restrict data to \n",
    "        \n",
    "    Returns: \n",
    "        regionalDataset (xr Dataset): dataset with restricted data to input regions\n",
    "    \"\"\"\n",
    "    \n",
    "    def checkKeys(regionKeyList, regionTbl): \n",
    "        \"\"\"Check that regionKeyList was defined correctly\n",
    "\n",
    "        Raises: \n",
    "            ValueError if regionKeyList was not defined correctly \n",
    "            warning if all data was removed from the dataset\n",
    "        \"\"\"\n",
    "        if type(regionKeyList) != list: #raise a ValueError if regionKeyList is not a list \n",
    "            raise ValueError('regionKeyList needs to be a list. \\nFor example, if you want to restrict data to the Beaufort Sea, define regionKeyList = [13]')\n",
    "\n",
    "        for key in regionKeyList: \n",
    "            if key not in list(regionTbl['key']): \n",
    "                raise ValueError('Region key ' + str(key) + ' does not exist in region mask. \\n Redefine regionKeyList with key numbers from table')\n",
    "\n",
    "        if len(regionKeyList) == 0: \n",
    "            warnings.warn('You removed all the data from the dataset. Are you sure you wanted to do this? \\n If not, make sure the list regionKeyList is not empty and try again. \\n If you intended to keep data from all regions, set regionKeyList = list(tbl[\\\"key\\\"])')\n",
    " \n",
    "    #create a table of keys and labels\n",
    "    regionMask = dataset.region_mask.attrs\n",
    "    regionTbl = pd.DataFrame({'key': regionMask['keys'], 'label': regionMask['labels']})\n",
    "    \n",
    "    #call function to check if regionKeyList was defined correctly\n",
    "    checkKeys(regionKeyList, regionTbl)\n",
    "    \n",
    "    #keys to remove (all keys that are note listed in regionKeyList)\n",
    "    keysToRemove = [key for key in list(regionTbl['key']) if key not in regionKeyList]\n",
    "    \n",
    "    #filter elements from the ice thickness DataArray where the region is the desired region\n",
    "    regionalDataset = dataset.copy()\n",
    "    for var in dataset.data_vars: \n",
    "        if var != 'seaice_conc_monthly_cdr':\n",
    "            regionalVar = regionalDataset[var]\n",
    "            for key in keysToRemove: \n",
    "                regionalVar = regionalVar.where(regionalVar['region_mask'] != key)\n",
    "            regionalDataset[var] = regionalVar\n",
    "    \n",
    "    #find name of labels \n",
    "    labels = [regionTbl[regionTbl['key'] == key]['label'].item() for key in regionKeyList]\n",
    "    \n",
    "    #add new attributes describing changes made to the dataset\n",
    "    if len(labels) < len(regionTbl['key']): \n",
    "        if set(regionKeyList) == set([10,11,12,13,15]): #convert to sets so unordered lists are compared\n",
    "            regionalDataset.attrs['regions with data'] = 'Inner Arctic'\n",
    "        else:    \n",
    "            regionalDataset.attrs['regions with data'] = ('%s' % ', '.join(map(str, labels)))\n",
    "        print('Regions selected: ' + regionalDataset.attrs['regions with data'])\n",
    "    else: \n",
    "        regionalDataset.attrs['regions with data'] = 'All'\n",
    "        print('Regions selected: All \\nNo regions will be removed')\n",
    "    \n",
    "    return regionalDataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#define a list of keys corresponding to the region of interest\n",
    "regionKeyList = [10,11,12,13,15] #Inner Arctic\n",
    "\n",
    "#restrict data to that region\n",
    "regionalDataset = restrictRegionally(dataset, regionKeyList)\n",
    "\n",
    "#plot regional data\n",
    "plotOneMonth(regionalDataset, dataVar = 'ice_thickness_filled', month = 'Feb 2019', minval = 0, maxval  = 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot winter data \n",
    " - This function is modified from the plotOneMonth function above to plot 6 months of data instead of one\n",
    " - Winter is defined as the months Nov, Dec, Jan, Feb, Mar, Apr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define plotting function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plotWinterMaps(dataset, dataVar, minval, maxval, cbarTicks = None, title = \"\", cmap = 'viridis', figPath = None):\n",
    "    \"\"\"Plot maps of the arctic on North Pole Stereo projection with several months of data overlayed, along with the sea ice edge for each month. \n",
    "   \n",
    "    Args:\n",
    "        dataset (xr Dataset): dataset from google bucket\n",
    "        dataVar (str): variable of interest\n",
    "        minval, maxval (int): minimum and maximum values for the data variable \n",
    "        cbarTicks (list or np array of length 2): ticks to use on colorbar (default to [minval + 1, maxval +1])\n",
    "        title (str, optional): title of subplots (default to empty string)\n",
    "        cmap (str, optional): color map (default to viridis)\n",
    "        figPath (str, optional): path to save fig (default to None)\n",
    "        \n",
    "    Returns:\n",
    "        Figure displayed in notebook \n",
    "\n",
    "    \"\"\"\n",
    "    #define projection and transform\n",
    "    proj = ccrs.NorthPolarStereo(central_longitude = -45)\n",
    "    transform = ccrs.PlateCarree()\n",
    "    \n",
    "    #initialize figure and axes\n",
    "    fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(7.8, 5.8), subplot_kw={'projection': proj})\n",
    "    \n",
    "    for i in range(len(dataset.time)):\n",
    "        ax = axs.flatten()[i]\n",
    "        \n",
    "        #plot data \n",
    "        im = dataset[dataVar].where(dataset['seaice_conc_monthly_cdr'] > 0.5).isel(time = i).plot(x = 'longitude', y = 'latitude', vmin = minval, vmax = maxval, extend = 'both', \n",
    "                    ax = ax, add_colorbar = False, transform = transform, zorder = 2, cmap = cmap)\n",
    "    \n",
    "        #plot sea ice concentration \n",
    "        SICarray = dataset['seaice_conc_monthly_cdr'].where(dataset['region_mask']!=21).isel(time = i) #dont plot contour along coastlines\n",
    "        lonGreater = ma.masked_greater(SICarray.longitude.values, -0.01)\n",
    "        lonLesser = ma.masked_less(SICarray.longitude.values, 0)\n",
    "        latGreater = ma.MaskedArray(SICarray.latitude.values, mask = lonGreater.mask)\n",
    "        latLesser = ma.MaskedArray(SICarray.latitude.values, mask = lonLesser.mask)\n",
    "        dataGreater = ma.MaskedArray(SICarray.values, mask = lonGreater.mask)\n",
    "        dataLesser = ma.MaskedArray(SICarray.values, mask = lonLesser.mask)\n",
    "        im2a = ax.contour(lonGreater, latGreater, dataGreater, levels = [0.5], transform = transform, colors = 'magenta', linewidths = 0.8, zorder = 5, alpha = 1)\n",
    "        im2b = ax.contour(lonLesser, latLesser, dataLesser, levels = [0.5], transform = transform, colors = 'magenta', linewidths = 0.8, zorder = 5, alpha = 1)\n",
    "        \n",
    "        #add features to map\n",
    "        ax.coastlines(linewidth=0.25, color = 'black', zorder = 10) #add coastlines \n",
    "        ax.add_feature(cfeature.LAND, color ='0.95', zorder = 5) #add land \n",
    "        ax.add_feature(cfeature.LAKES, color = 'grey', zorder = 5) #add lakes \n",
    "        ax.gridlines(draw_labels = False, linewidth = 0.25, color = 'gray', alpha = 0.75, linestyle='--', zorder = 6) #add gridlines\n",
    "        ax.set_extent([-179, 179, 50, 90], crs = transform) #zoom in so map only displays the Arctic\n",
    "        ax.set_title(pd.to_datetime(dataset.time.values).strftime('%B %Y')[i])\n",
    "            \n",
    "    #adjust subplots\n",
    "    fig.subplots_adjust(bottom=0.1, top=0.9, wspace=0.05, hspace=0.13)\n",
    "    \n",
    "    #add a title\n",
    "    plt.suptitle(\"\\n\".join(wrap(title + ': ' + dataset[dataVar].attrs['long_name'], 55)), fontsize = 18, y = 1.015, fontweight = 'medium')\n",
    "\n",
    "    #add colorbar\n",
    "    cax = fig.add_axes([0.34, 0.02, 0.35, 0.025])\n",
    "    cb = fig.colorbar(im,cax = cax,extend='both',orientation = 'horizontal')\n",
    "    cbarTicks = np.arange(minval, maxval + 1, 1) if cbarTicks is None else cbarTicks\n",
    "    cb.set_ticks(cbarTicks)\n",
    "    cb.set_label(\"\\n\".join(wrap(dataset[dataVar].attrs['long_name'] + ' (' + dataset[dataVar].attrs['units'] + ')', 38)), fontsize = 10)\n",
    "\n",
    "    #tight layout\n",
    "    plt.tight_layout()\n",
    "    \n",
    "    #save figure\n",
    "    if figPath != None:\n",
    "        plt.savefig(figPath, dpi = 200)\n",
    "    \n",
    "    #display figure\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plot maps for different data variables\n",
    "Here, we will call the winter plotting function on some of the variables in the dataset using different arguments for minimum & maximum values and colormap to allow for visualization of the data. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ICESat-2 sea ice thickness"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'ice_thickness_filled',\n",
    "               minval = 0, maxval = 4, title = 'Winter 2018-19')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'ice_thickness_filled',\n",
    "               minval = 0, maxval = 4, title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### PIOMAS sea ice thickness "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'PIOMAS_ice_thickness', \n",
    "               minval = 0, maxval = 4, title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'PIOMAS_ice_thickness',\n",
    "               minval = 0, maxval = 4, title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ICESat-2 sea ice thickness uncertainty\n",
    "This variable describes systematic uncertainty in the sea ice thickness measurement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'ice_thickness_unc_filled', \n",
    "               minval = 0, maxval = 1, cmap = 'plasma', title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'ice_thickness_unc_filled', \n",
    "               minval = 0, maxval = 1, cmap = 'plasma', title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### OSI-SAF ice type"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'ice_type_filled',\n",
    "               minval = 0, maxval = 1, cmap = 'YlOrRd', title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'ice_type_filled', \n",
    "               minval = 0, maxval = 1, cmap = 'YlOrRd', title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ERA5 2-meter temperature "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 't2m', cbarTicks = np.arange(-40,-20 + 5, 5),\n",
    "               minval = -40, maxval = -20, cmap = 'coolwarm', title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 't2m', cbarTicks = np.arange(-40,-20 + 5, 5),\n",
    "               minval = -40, maxval = -20, cmap = 'coolwarm', title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ERA5 mean surface downward long-wave radiation flux"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'msdwlwrf', cbarTicks = np.arange(150,250 + 25, 25),\n",
    "               minval = 150, maxval = 250, cmap = 'PuRd', title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'msdwlwrf', cbarTicks = np.arange(150,250 + 25, 25),\n",
    "               minval = 150, maxval = 250, cmap = 'PuRd', title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### NSIDC sea ice motion vectors\n",
    "See the [sea ice drift](https://nicolejkeeney.github.io/icesat2-book/ice_drift.html) notebook for more information on how to plot this variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2018-2019\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2018', 'Apr 2019')), dataVar = 'drifts_magnitude', cbarTicks = np.arange(0,15 + 5, 5),\n",
    "               minval = 0, maxval = 15, cmap = 'YlGnBu', title = 'Winter 2018-2019')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#winter 2019-2020\n",
    "plotWinterMaps(dataset.sel(time = slice('Nov 2019', 'Apr 2020')), dataVar = 'drifts_magnitude', cbarTicks = np.arange(0,15 + 5, 5),\n",
    "               minval = 0, maxval = 15, cmap = 'YlGnBu', title = 'Winter 2019-2020')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A note on selecting time ranges "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Xarray is a great tool to use with time series data because it is easy to restrict data to a time range or month. To restrict data to a single month, you can select that month by inputting the month as a string in a number of different ways to get the same result. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dataset.sel(time = 'Jan 2019').time.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dataset.sel(time = 'January 2019').time.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dataset.sel(time = '2019-01').time.values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note how all three strings to represent January 2019 outputted the same results. <br><br>Xarray also allows you to easily select a range of data. Using the same format, you can select a slice of months representing a range of consecutive months. This is how the data was selected in the winter plotting section. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dataset.sel(time = slice('Nov 2019', 'Apr 2020')).time.values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thus giving us the corresponding date values for the months November 2019, December 2019, January 2020, February 2020, March 2020, and April 2020."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
